import Json from '@/data/ResultJson'
import { AutoId } from '@/data/AutoId'
const roleList = [
  { id: 1, name: '管理员', profile: '管理员', status: 1 },
  { id: 2, name: '会员', profile: '会员', status: 1 },
  { id: 3, name: '用户', profile: '用户', status: 2 }
]
function getIndexById (id) {
  id = parseInt(id)
  let index = -1
  for (let i = 0; i < roleList.length; i++) {
    if (roleList[i].id === id) {
      index = i
      break
    }
  }
  if (index === -1) {
    return Json.error('编号异常！')
  }
  return index
}

export function getRoleListAjax (searchInfo = {}) {
  let dataList = roleList.filter(item => item.name === searchInfo.name || !searchInfo.name)
  dataList = dataList.filter(item => item.status === searchInfo.status || !searchInfo.status)
  dataList = dataList.reverse()
  return Json.success(dataList)
}

export function deleteRoleAjax (id) {
  if (id === 1) {
    return Json.error('管理员禁止删除')
  }
  const index = getIndexById(id)
  roleList.splice(index, 1)
  return Json.success()
}

export function getRoleByIdAjax (id) {
  const index = getIndexById(id)
  return Json.success({ ...roleList[index] })
}

export function saveOrUpdate (formData = {}) {
  if (formData.id) {
    const index = getIndexById(formData.id)
    roleList[index] = { ...formData }
  } else {
    for (const role of roleList) {
      if (role.name === formData.name) {
        return Json.error('角色已存在')
      }
    }
    formData.id = AutoId.roleId
    roleList.push(formData)
    AutoId.roleId++
  }
  return Json.success()
}
